import { Router, createRouter, createWebHistory, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import routes from "./routes";
import store from "../store/index"
// import { useDispatch } from "vuex"
const router: Router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior(to, from, savedPosition) {
        // 如果当前路由没有匹配成功，则跳转到 404 页面
        if (to.name === null) {
            return { path: '/404' };
        }

        return savedPosition || { top: 0 };
    },
});

// const store = useStore();

// 在导航守卫中是使用next进行跳转
router.beforeEach(async (to, from, next) => {
    const state = store.state;
    // 判断
    if (to.path === "/login") {
        store.dispatch('user/removeLogin')
        next();
    } else {
        // 判断有无
        if (state.user.user.loginId) {
            next();
        } else {
            // 无进行执行whoami还没有则进行无法跳转
            const data = await store.dispatch("user/whoAmi");
            if (data?.id) {
                next();
            } else {
                // 警告
                ElMessage({
                    message: "管理员未登录,请先进行登录！",
                    type: "warning",
                    duration: 1500
                })
                next("/login");
            }
        }

    }

})

export default router;